package tools

import (
	"mime/multipart"
	"os"
	"path"
	"strings"
	"time"

	. "gddgame.cc/galaxy/common/dsl/db"
	. "gddgame.cc/galaxy/common/dsl/web"
	"gddgame.cc/galaxy/core/config"
	"gddgame.cc/galaxy/utils"
	"gddgame.cc/galaxy/utils/def"
	"gddgame.cc/galaxy/utils/orm"
	"gddgame.cc/galaxy/utils/uuid"
)

var (
	ToolsExcelModel = orm.NewModel("tools_excel", &ToolsExcel{}, nil)
)

func GetExcelTable() *Table {
	return &Table{
		Model: ToolsExcelModel,
		Add: &TableHandle{
			Controller: func(context def.Context, name string, file *multipart.FileHeader) (*ToolsExcel, error) {
				var toolsExcel ToolsExcel
				var err error
				f, err := file.Open()
				if err != nil {
					return nil, err
				}
				localFile, url := toolsExcel.GetFile(config.UploadPath, config.UploadUrl)
				if err := utils.CopyFile(f, localFile); err != nil {
					return nil, err
				}
				toolsExcel = ToolsExcel{
					Name: name,
					Path: url,
				}
				_, err = ToolsExcelModel.Insert(&toolsExcel)
				if err != nil {
					return nil, SystemExceptionDetail("excel添加失败", err)
				}
				return &toolsExcel, nil
			},
			Params: []Param{
				{Name: "name", In: Form},
				{Name: "file", In: File},
			},
		},
		Edit: &TableHandle{
			Controller: func(context def.Context, id int, name string, file *multipart.FileHeader) error {
				var toolsExcel ToolsExcel
				var err error
				if ok, err := ToolsExcelModel.PK(id).One(&toolsExcel); !ok {
					return EmptyExceptionDetail("excel不存在", err)
				}
				f, err := file.Open()
				if err != nil {
					return err
				}
				localFile, _ := toolsExcel.GetFile(config.UploadPath, config.UploadUrl)
				if err := os.Remove(localFile); err != nil {
					return err
				}
				toolsExcel.Path = ""
				localFile, url := toolsExcel.GetFile(config.UploadPath, config.UploadUrl)
				if err := utils.CopyFile(f, localFile); err != nil {
					return err
				}
				_data := make(map[string]interface{})
				_data["name"] = name
				_data["path"] = url
				_, err = ToolsExcelModel.PK(id).Update(_data)
				if err != nil {
					return SystemExceptionDetail("excel更新失败", err)
				}
				return nil
			},
			Params: []Param{
				{Name: "id", In: Path, Type: Int},
				{Name: "name", In: Form},
				{Name: "file", In: File},
			},
		},
	}
}

type ToolsExcel struct {
	Id   int    `json:"id" orm:"auto" sql:"INT"`
	Name string `json:"name" sql:"VARCHAR"`
	Path string `json:"path" sql:"VARCHAR"`

	CreateTime *time.Time `json:"create_time" orm:"createTime" sql:"DATETIME"`
	UpdateTime *time.Time `json:"update_time" orm:"updateTime" sql:"DATETIME"`
	DeleteTime *time.Time `json:"delete_time" orm:"deleteTime" sql:"DATETIME"`
}

func (toolsExcel *ToolsExcel) GetFile(uploadPath string, uploadUrl string) (string, string) {
	var filename string
	if toolsExcel.Path != "" {
		// 保持文件名
		filename = strings.Replace(toolsExcel.Path, uploadUrl, "", 1)
	} else {
		// 新建文件
		filename = uuid.RandomString()
		toolsExcel.Path = path.Join(uploadUrl, filename)
	}
	return path.Join(uploadPath, filename), toolsExcel.Path
}
